package lt.mockos.app.client.cpu.hw;

import java.util.LinkedList;

import lt.mockos.app.client.cpu.hw.descriptor.ProcessDescriptor;
import lt.mockos.app.client.cpu.hw.descriptor.ResourceDescriptor;
import lt.mockos.app.client.cpu.hw.descriptor.ResourceDescriptor.Channel;
import lt.mockos.app.client.cpu.hw.type.ProcessStatus;

public class ResourcesManager {

    public SuperMemory superMemory;

    public ResourcesManager(SuperMemory superMemory) {
        this.superMemory = superMemory;
    }

    private LinkedList<ProcessDescriptor> processes;

    public ResourceDescriptor createResource(String title, ProcessDescriptor parent, Channel channel) {
        ResourceDescriptor rd = new ResourceDescriptor(title, parent, channel);
        superMemory.add(rd);

        return rd;
    }

    public void removeResource(ResourceDescriptor rd, ProcessDescriptor pd) {
        if (rd.getParent() == pd)
            superMemory.remove(rd);
    }

    public void askResource(ResourceDescriptor rd, ProcessDescriptor pd) {
        pd.setAskedResource(rd);
        if (rd.getUsingProcess() == null) {
            rd.setUsingProcess(pd);
        }
        else {
            pd.setStatus(ProcessStatus.BLOCK);
        }
            
    }

    public void freeResource(ResourceDescriptor rd) {
        ProcessDescriptor pd = rd.getUsingProcess();
        if (pd != null){
            pd.setAskedResource(null);
            rd.setUsingProcess(null);
        }
    }

}
